package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.IdWorker;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;



    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size) throws Exception {

        String sn = (String) searchMap.get("sn");

        String name = (String) searchMap.get("name");

        String brandName = (String) searchMap.get("brandName");
        Integer brandId = brandMapper.findIdByBrandName(brandName);

        String categoryName=(String) searchMap.get("categoryName");
        Integer categoryId = categoryMapper.findIdBycategoryName(categoryName);

        PageHelper.startPage(page,size);
        Example example = createExample(sn,name,brandId,categoryId);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    //添加更新
    @Override
    public Integer spuAdd(Spu spu) {

        return spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 第一步添加商品
     * zxq
     * @param spu
     */
    @Override
    public void addFirst(Spu spu) {
        spuMapper.insertSelective(spu);
    }

    @Override
    public int updataOnline(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        String isMarketable = spu.getIsMarketable();
        if (isMarketable.equals("1")) {
            spu.setIsMarketable("0");
        }else {
            spu.setIsMarketable("1");
        }
        return spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品对应分类的规格参数(模板)查询_参数查询
     * @param id
     * @return
     */
    @Override
    public List<String> findTemplateById(Long id) {
        String options = spuMapper.findTemplateById(id);
        List<String> list = new ArrayList<>();
        if (options != null && options.length()>0){
            String[] split = options.split(",");
            for (String s : split) {
                list.add(s);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> findByPage(int page, int size, String is_marketable, String status) {
        return null;
    }

    /**
     * 构建查询对象 searchMap
     * @param
     * @return
     */
    private Example createExample(String sn,String name,Integer brandId,Integer categoryId){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

            // 货号
            if(sn!=null && !"".equals(sn)){
                criteria.andEqualTo("sn",sn);
            }
            // SPU名
            if(name!=null && !"".equals(name)){
                criteria.andLike("name","%"+name+"%");
            }
            // 品牌ID
            if(brandId!=null ){
                criteria.andEqualTo("brandId",brandId);
            }
             // 分类
             Example.Criteria criteria1 = example.createCriteria();
            if(categoryId!=null ){
             criteria1.orEqualTo("category1Id",categoryId).orEqualTo("category2Id",categoryId).orEqualTo("category3Id",categoryId);
         }
              example.and(criteria1);
         return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional
    public void delete(String id){
        //逻辑删除
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断当前商品是否处于下架状态
        if (!spu.getIsMarketable().equals("0")){
            throw new RuntimeException("当前商品必须处于下架状态才能删除");
        }
        //如果是下架状态,修改相对应的标记为进行逻辑删除
        spu.setIsDelete("1");
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 更新添加商品
     * @param goods
     */
    @Transactional
    @Override
    public void add(Goods goods){
        //1.添加spu
        Spu spu = goods.getSpu();
        //设置分布式id
        long spuId = idWorker.nextId();
        spu.setId(String.valueOf(spuId));
        //设置删除状态.
        spu.setIsDelete("0");
        //上架状态
        spu.setIsMarketable("0");
        //审核状态
        spu.setStatus("0");
        spuMapper.insertSelective(spu);

        //2.添加sku集合
        this.saveSkuList(goods);
    }

    //添加sku数据
    private void saveSkuList(Goods goods) {
        Spu spu = goods.getSpu();
        //查询分类对象
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        //查询品牌对象
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());

        //设置品牌与分类的关联关系
        //查询关联表
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count == 0){
            //品牌与分类还没有关联关系
            categoryBrandMapper.insert(categoryBrand);
        }

        //获取sku集合
        List<Sku> skuList = goods.getSkuList();
        if (skuList != null){
            //遍历sku集合,循环填充数据并添加到数据库中
            for (Sku sku : skuList) {
                //设置skuId
                sku.setId(String.valueOf(idWorker.nextId()));
                //设置sku规格数据
                if (StringUtils.isEmpty(sku.getSpec())){
                    sku.setSpec("{}");
                }
                //设置sku名称(spu名称+规格)
                String name = spu.getName();
                //将规格json转换为map,将map中的value进行名称的拼接
                Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                if (specMap != null && specMap.size()>0){
                    for (String value : specMap.values()) {
                        name+=" "+value;
                    }
                }
                sku.setName(name);
                //设置spuid
                sku.setSpuId(spu.getId());
                //设置创建与修改时间
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                //商品分类id
                sku.setCategoryId(category.getId());
                //设置商品分类名称
                sku.setCategoryName(category.getName());
                //设置品牌名称
                sku.setBrandName(brand.getName());
                //将sku添加到数据库
                skuMapper.insertSelective(sku);

            }
        }
    }

}
